<?php
namespace app\controllers; //命名空间

use yii\web\Controller; // 导入Controller
use app\controllers\BaseController; //导入基础controller（内含各种基础使用函数）
//导入模型
use app\models\User;			//用户模型
use app\models\UserFiction;		//用户收藏小说模型
use app\models\FictionType;		//小说类型模型
use app\models\Fiction;			//小说模型
use app\models\FictionRecord;	//小说记录模型
use app\models\FictionChapter;	//小说章节内容模型

use yii\web\Session;
use Yii; // 导入Yii
/****
小说有关功能：
1、显示：全部显示、
        排行榜显示、（阅读量、收藏量）
        类型显示、
        更新显示、
        推荐显示（以当天更新且热度高的前三个小说为例）、
2、搜索：名字搜索、
3、用户收藏：收藏功能、
            观看收藏内容(按照更新时间排序)
4、阅读历史：内容：{阅读集页、阅读时间}
****/
/***
Showall       显示全部小说
Showfindfic   查询相应小说              
Showrank      显示排行榜包括阅读量、收藏量          
Showfic       显示单一小说                      
Showtype      显示单一类型的小说 
Showfconfig   显示全部类型
Showtopthree  显示收藏量top3的小说
Showupdate    显示最新更新的小说
Collect       用户功能：收藏
Uncollect     用户功能：取消收藏
Showcollect   用户功能：查看全部收藏
Showhistory   用户功能：阅读历史
Reading       用户功能：记录用户阅读历史、小说阅读量
***/

class FictionController extends Controller{
    //在Yii框架中，为了防止csrf攻击，封装了CSRF令牌验证
    public $enableCsrfValidation = false;

	//总函数 经商讨 使用关键字返回的形式那么
	public function actionIndex(){
		//根据参数返回来确定功能 详细参数看注释
        if( Yii::$app->request->isPost ){
            //数据初始化
            //负责调用全部action函数的单一函数
            /*
              Showall       显示全部小说关键字
              Showfindfic   查询相应小说                    
              Showrank      显示排行榜包括阅读量、收藏量          
              Showfic       显示单一小说                     
              Showtype      显示单一类型的小说
              Showfconfig   显示全部类型
              Showtopthree  显示收藏量top3的小说
              Showupdate    显示最新更新的小说
              Collect       用户功能：收藏
              Uncollect     用户功能：取消收藏
              Showcollect   用户功能：查看全部收藏
              Showhistory   用户功能：阅读历史
              Reading       用户功能：记录用户阅读历史、小说阅读量
            */ 
            $postData = Yii::$app->request->post();					//接收function，及其其他参数
            $function = $postData['function'];
            switch ($function) {
                case 'Showall':
                    $data = $this->function_Showall();				//不需要任何参数
                    break;

                case 'Showfindfic':
                    $data = $this->function_Showfindfic($postData);	//需要参数'fName'
                    break;

                case 'Showrank':
                    $data = $this->function_Showrank($postData);	//需要的参数的'rank' : 'collection' / 'read'
                    break;

                case 'Showfic':
                    $data = $this->function_Showfic($postData);		//需要的参数为 'fId'、'session' : '有'或者'NULL'
                    break;

                case 'Showtype':
                    $data = $this->function_Showtype($postData);	//需要的参数 fTid
                    break;

                case 'Showfconfig':
                    $data = $this->function_Showfconfig();			//不需要参数
                    break;

                case 'Showtopthree':
                    $data = $this->function_Showtopthree();			//不需要参数
                    break;

                case 'Showupdate':
                    $data = $this->function_Showupdate();			//不需要参数
                    break;

                case 'Collect':
                    $data = $this->function_Collect($postData);		//需要的参数session、fId
                    break;

                case 'Uncollect':
                    $data = $this->function_Uncollect($postData);	//需要的参数fId、session
                    break;

                case 'Showcollect':
                    $data = $this->function_Showcollect($postData);	//需要参数session
                    break;

                case 'Showhistory':
                    $data = $this->function_Showhistory($postData);	//需要的参数session
                    break;

                case 'Reading':
                    $data = $this->function_Reading($postData);		//需要的参数session、fId、reading
                    break;
                default:
                    $content = '不存在此种功能';
                    $data = array(
                        '0' => 0,
                        '1' => $content,
                    );
                    return BaseController::FailRespone($data);
                    break;
            }
            return BaseController::EveryResponse($data);
            exit(0);
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
	}

	//小说全部显示
	//小说储存在服务器上 
	//这边主要储存路径
	//此外做一个上传的函数
	//业务逻辑：先显示所有小说（形式为最新更新的小说）返回的形式以数组形式返回 --- 
    //数组形式为 {
    //           [0]:{
    //                ['fId']:......小说id
    //                ['fCover']:...封面
    //                ['fName']:....名称
    //                ['fAuthor']:..作者
    //                }
    //           [1]:{
	//                与上类似
	//               }
    //            }
    //当确定某小说时就返回详细名称从而返回集数
	public function function_Showall(){		//不需要任何参数
        //数据初始化
        $fictions = Fiction::getAll();
        if(empty($fictions)){
        	$content = '数据错误，没有搜到任何小说';
        	$data = array(
                '0' => -3, 
                '1' => $content,
            );
            return $data;
        }
        $data = array(
            '0' => 1,
            '1' => $fictions,
        );
        return $data;
	}

    //全局查找，根据关键字查找小说
    public function function_Showfindfic($postData){	//需要参数'fName'
        if(empty($postData['fName'])){
            //当没有uId时的报错返回
            $content = "请输入你要查找的小说";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }
        //数据初始化
        //接收数据
        $fName = $postData['fName'];
        //查找
        $search_result = Fiction::getSearch($fName);
        if(!$search_result){
            //当没有uId时的报错返回
            $content = "查询不到你要的小说";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        $data = array(
            '0' => 1,
            '1' => $search_result,
        );
        return $data;
    }

	//小说排行榜显示（两个参数-阅读量、收藏量）//前10 或前20 
	public function function_Showrank($postData){	//需要的参数的'rank' : 'collection' / 'read'
        //数据初始化
        //接收数据
		$rank = $postData['rank'];  //参数为 collection read
		if($rank == 'collection'){
			$fictions = Fiction::getBycollection();
		}else if($rank == 'read'){
			$fictions = Fiction::getByreadcount();
		}
		if(empty($fictions)){
			$content = '暂时没查到任何小说';
			$data = array(
                '0' => 0, 
                '1' => $content,
            );
            return $data;
		}
        $data = array(
            '0' => 1,
            '1' => $fictions,
        );
		return $data;
	}

    //数组：array{ 'fId','fName','fAuthor','fCover','fCollection','fReadcount','fSaveurl','fNowupdate','fUpdatetime','collect'} //封面，名字，作者，储存路径，最新集数，
	//看详细某一部小说
    //商量 是前端使用逻辑 还是后端返回集数 然后返回逻辑

    #*****增加一个此小说观看到某一部分逻辑
	public function function_Showfic($postData){	//需要的参数为 'fId'、'session' : '有'或者'NULL'
        //判断数据是否齐全
        if(empty($postData['fId'])){
             //当没有uId时的报错返回
            $content = "请输入fId";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }else if (empty($postData['session'])) {
            $postData['session'] = NULL;
        }
        //数据初始化
        //接收数据
        $fId = $postData['fId'];  //参数为 fId 小说的id
        $session = $postData['session']; //有登录传session 没登录传null
        $uId = BaseController::Check_session($session); //检查是否登录
        if(empty($fId)){
            $content = '请输入fId';
            $data = array(
                '0' => 0, 
                '1' => $content,
            );
            return $data;
        }
        //查找小说详细信息
        $fiction_info = Fiction::getByfId($fId);
        if(!isset($fiction_info)){
            $content = '暂时未找到小说';
            $data = array(
                '0' => 0, 
                '1' => $content,
            );
            return $data;
        }
        //检查小说是否被用户所收藏
        if(!$uId){
            $fiction_info['collect'] = false;
        }else{
            $user_fiction_info = array(
                'uId' => $uId,
                'fId' => $fId,
            );
            $check_result = UserFiction::checkByuIdfId($user_fiction_info);
            $fiction_info['collect'] = $check_result;
        }
        //储存路径
        $saveurl = $fiction_info['fSaveurl'];
        //所拥有的卷
        $books = $fiction_info['fNowupdate'];
        //小说卷数及其各章的储存路径、还有标题
        $books_info = $this->Deal_book($fId, $saveurl, $books);
        if(!$books_info){
            $content = '暂时未找到小说';
            $data = array(
                '0' => 0, 
                '1' => $content,
            );
            return $data;
        }

        //查看此小说阅读历史
        $user_record = FictionRecord::getHisByuIdfId($uId, $fId);
        if(!empty($user_record)){
            $fiction_info['history']['read'] = true;
            $fiction_info['history']['readagain'] = $this->Deal_OneFictionRecord($user_record);
        }else{
            $book = '1';
            $chapter = FictionChapter::getChapter($fId, $book);
            //创建新的阅读历史
            $new_record = array(
                'fId' => $fId,
                'uFReading' => '1/'.$chapter[0]['fChapter'],
            );
            $fiction_info['history']['read'] = false;
            $fiction_info['history']['readagain'] = $this->Deal_OneFictionRecord($new_record);
        }
        //小说卷数的详细信息
        $fiction_info['books_info'] = $books_info;
        //查看用户对于此小说阅读历史
        $data = array(
            '0' => 1,
            '1' => $fiction_info,
        );
        return $data;
	}
    
    //独立一个接口
	//小说类型显示
	public function function_Showtype($postData){ //需要的参数 fTid
        //数据初始化
        //接收数据
		$fTid = $postData['fTid'];
		$fictions = Fiction::getBytype($fTid);
		if(empty($fictions)){
			$content = '暂时没查到任何这种类型小说';
			$data = array(
                '0' => 0, 
                '1' => $errorContent,
            );
            return $data;
		}
        $data = array(
            '0' => 1,
            '1' => $fictions,
        );
		return $data;
	}

	//小说类型显示
	public function function_Showfconfig(){  //不需要参数
		$types = FictionType::getAlltype();
        $data = array(
            '0' => 1,
            '1' => $types,
        );
		return $data;
	}

    //推荐小说显示（前三）首页 滚动页
    public function function_Showtopthree(){ //不需要参数
        //数据初始化
        $fictions = Fiction::getByUpdatetopthree();
        if(empty($fictions)){
            $content = '暂时没查到任何更新小说';
            $data = array(
                '0' => 0, 
                '1' => $errorContent,
            );
            return $data;
        }
        $data = array(
            '0' => 1,
            '1' => $fictions,
        );
        return $data;
    }

    //小说更新列表显示
    public function function_Showupdate(){ //不需要参数
        //数据初始化
        $fictions = Fiction::getByUpdatetopten();
        if(empty($fictions)){
            $content = '暂时没查到任何更新小说';
            $data = array(
                '0' => 0, 
                '1' => $errorContent,
            );
            return $data;
        }
        $fictions_info = $this->Deal_UpdateFictions($fictions);
        $data = array(
            '0' => 1,
            '1' => $fictions_info
        );
        return $data;
    }

    /****某一用户系列功能****/

    //用户点击收藏小说
    //收藏标示
    public function function_Collect($postData){ //需要的参数fId、session
        //判断数据是否齐全
        if(empty($postData['fId'])){
             //当没有uId时的报错返回
            $content = "请输入fId";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }
        //赋值
        $fId = $postData['fId'];       //小说id
        $session = $postData['session']; //用户标识id
        $uId = BaseController::Check_session($session); //得出用户的uId
        if(!$uId){
            //当没有uId时的报错返回
            $content = "请登录再收藏";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
         $user_fiction = array(
            'uId' => $uId, //用户id
            'fId' => $fId, //小说id
        );
        //避免延迟重复点击收藏
        $user = UserFiction::checkByuIdfId($user_fiction);
        if($user){
            $content = "此用户已收藏小说";
            $data = array(
                '0' => 1,
                '1' => $content,
            );
            return $data;
        }
        //先检查数据库是否存在用户收藏这小说的信息
        $user = UserFiction::checkByuId($uId);
        if($user){
            //更新用户的state
            $user_result = UserFiction::updateOnState($user_fiction);
        }else{ 
            //用户的收藏小说录入数据库的信息
            //添加数据到userfiction
            $user_result = UserFiction::add($user_fiction);
        }
        //此id小说的收藏量+1
        $collect_result = Fiction::updateCollection($fId);
        if(!$user_result){
            $content = '收藏失败，请重新尝试';
            $data = array(
                '0' => -1, 
                '1' => $content,
            );
            return $data;
        }
        $result = array(
            'collect' => true,
            'content' => '收藏成功',
        );
        $data = array(
            '0' => 1,
            '1' => $result,
        );
        return $data;
    }
    
    //取消收藏
    public function function_Uncollect($postData){ //需要的参数fId、session
        //判断数据是否齐全
        if(empty($postData['fId'])){
             //当没有uId时的报错返回
            $content = "请输入fId";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }
        //数据初始化
        //接收数据
        $fId = $postData['fId'];       //小说id
        $session = $postData['session']; //用户标识id
        $uId = BaseController::Check_session($session); //得出用户的uId
        //当没有uId时的报错返回
        if(!$uId){
            $content = "请登录再收藏";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //用户的收藏小说录入数据库的信息
        $user_fiction = array(
            'uId' => $uId, //用户id
            'fId' => $fId, //小说id
        );
        //添加数据到userfiction
        $user_result = UserFiction::updateOffState($user_fiction);
        //此id小说的收藏量-1
        $collect_result = Fiction::updateUnCollection($fId);
        if(!$user_result){
            $content = '取消收藏失败，请重新尝试';
            $data = array(
                '0' => -1, 
                '1' => $content,
            );
            return $data;
        }
        $result = array(
            'collect' => false,
            'content' => '取消收藏',
        );
        $data = array(
            '0' => 1,
            '1' => $result,
        );
        return $data;
    }

    //显示用户收藏的小说
    //同时显示观看到的哪一部分并返回那一个url
    public function function_Showcollect($postData){ //需要的参数session
        //数据初始化
        //接收数据
        $session = $postData['session']; //用户标识id
        $uId = BaseController::Check_session($session); //得出用户的uId
        //当没有uId时的报错返回
        if(!$uId){
            $content = "请登录再查看你的收藏";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //根据uId搜索用户收藏了哪些小说
        $fictions_fId = UserFiction::getByuId($uId);
        if(empty($fictions_fId)){
            $content = "你还没有收藏任何小说，请去观看";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //根据fId小说详细的信息 分别为fId、name、cover、最新看到哪一集
        $user_fictions = $this->Deal_UserFiction($fictions_fId, $uId);
        $data = array(
            '0' => 1,
            '1' => $user_fictions,
        );
        return $data;
    }

    //用户观看历史显示
    public function function_Showhistory($postData){ //需要的参数session
        //数据初始化
        //接收数据
        $session = $postData['session']; //用户标识id
        $uId = BaseController::Check_session($session); //得出用户的uId
        //当没有uId时的报错返回
        if(!$uId){
            $content = "请登录再查看你的历史";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //根据uId搜索用户查看了哪些小说
        $fictions_record = FictionRecord::getAllByuId($uId);
        if(empty($fictions_record)){
            $content = "你还没有查看如何小说，请去观看";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //获取阅读过的小说的名字、封面
        //同时添加一个”继续阅读“的按钮功能-形式：添加继续阅读的标签 拥有数组数据为：'fId'、'储存路径'、'uCReading'
        $fictions_info = $this->Deal_FictionRecord($fictions_record);
        $data = array(
            '0' => 1,
            '1' => $fictions_info,
        );
        return $data;
    }

    //经晋康商量 得出用户每点击下一页或者第一页小说时 则请求一次接口 返回fId: 、history:(如：1/12)
    public function function_Reading($postData){ //需要的参数session、fId、reading
         //判断数据是否齐全
        if(empty($postData['fId'])){
            //当没有uId时的报错返回
            $content = "请输入fId";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }else if(empty($postData['reading'])){
            //当没有uId时的报错返回
            $content = "请输入reading";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }
        //数据初始化
        //接收数据
        $session = $postData['session']; //用户标识id
        $fId = $postData['fId']; //小说id
        $reading = $postData['reading']; //看到第几卷第几章
        $uId = BaseController::Check_session($session); //得出用户的uId
        //当没有uId时的报错返回
        if(!$uId){
            $content = "此用户没有登录，不需要记录历史";
            $result = array(
                'fId' => $fId,
                'content' => $content,
            );
            $data = array(
                '0' => 0, 
                '1' => $result,
            );
            return $data;
        }
            
        //每次阅读一集小说就传一个历史过来格式：1/10
        $record = array(
            'uId' => $uId,
            'fId' => $fId,
            'uFReading' => $reading,
        );
        //先检查是否存在这个用户历史
        $check_user = FictionRecord::getHisByuIdfId($uId, $fId);
        //当不存在时，将历史加入数据库，同时增加阅读量
        if(empty($check_user)){
            $result = FictionRecord::add($record);
            Fiction::updateReadcount($fId);
        }else{
            //更新用户阅读历史
            $result = FictionRecord::updateFReading($record);
        } 
        $result = true;
        if(!$result){
            $content = "请求数据失败，请刷新一遍再看";
            $data = array(
                '0' => -1,
                '1' => $content,
            );
            return $data;
        }
        //更新成功后返回一个状态码
        $result = array(
            'fId' => $fId,
            'content' => '阅读历史更新成功',
        );
        $data = array(
            '0' => 1,
            '1' => $result,
        );
        return $data;
    }   

    /********************/



    //上传小说
	public function actionLoadcom(){

	}

    /******/
    //外置函数的使用
    /*****/
    //显示小说集数的页面
    public function Deal_book($fId, $saveurl, $books){
        if($books > 0){
            $books_info = array();
            for($i = 1; $i <= $books; $i++){
                $chapters = FictionChapter::getChapter($fId, $i);
                //这一卷的开始路径
                $books_info[$i]['saveurl'] = $saveurl.$i.'/'.$chapters[0]['fChapter'].'.txt';
                //每一卷的卷数
                $books_info[$i]['book'] = $i;
                //每一卷固有名称
                $books_info[$i]['bookName'] = '第'.$i.'卷';
                //每一卷的章节数
                $books_info[$i]['chapters'] = count($chapters);
                //每一章的详细信息：章节序号、章节标题、章节路径
                foreach ($chapters as $key) {
                	//章节序号
                	$books_info[$i]['chapter_info'][$key['fChapter']]['chapter'] = $key['fChapter'];
                	//章节标题
                	$books_info[$i]['chapter_info'][$key['fChapter']]['chapterName'] = $key['fChapterName'];
                	//章节路径
                	$books_info[$i]['chapter_info'][$key['fChapter']]['saveurl'] = $saveurl.$i.'/'.$key['fChapter'].'.txt';
                }
            }
            return $books_info;
        }
        return false;
    }

    //处理小说详细信息
    public function Deal_UserFiction($fictions_fid, $uId){
        $user_fictions = array();
        $i = 0;
        foreach ($fictions_fid as $key) {
            $fId = $key['fId'];
            $fiction_info = Fiction::getInfoByfId($fId);
            $fiction_record = FictionRecord::getHisByuIdfId($uId, $fId);
            //小说的已更新集数
            $user_fictions[$i] = $fiction_info;
            $user_fictions[$i]['fNowupdate'] = '更新到'.$fiction_info['fNowupdate'].'卷';
            //小说已看到的地方
            if(empty($fiction_record)){
                $user_fictions[$i]['uFReading'] = '未开始观看';
            }else{
                $fiction_record = explode('/', $fiction_record['uFReading']);
                $book = $fiction_record['0'];
                $chapter = $fiction_record['1'];
                $user_fictions[$i]['uFReading'] = '看到第'.$book.'卷第'.$chapter.'章';
            }
            //下一个小说+1
            $i++;
        }
        return $user_fictions;
    }

    //处理小说历史的小说详细信息
    public function Deal_FictionRecord($fictions_record){
        $fictions_info = array();
        $i = 0;
        foreach ($fictions_record as $key) {
            $fId = $key['fId'];
            //将小说历史的集数页数进行分割
            $fiction_record = explode('/', $key['uFReading']);
            $book = $fiction_record['0'];
            $chapter = $fiction_record['1'];
            //获取小说的名字和封面
            $fiction_info = Fiction::getRecordInfoByfId($fId);
            //总章节数
            $book_info = FictionChapter::getChapter($fId, $book);
            //小说详细的信息、当前卷每个章节的信息
            $chapter_info = FictionChapter::getChapterName($fId, $book, $chapter);
            //小说主体信息
            //信息组合
            $fictions_info[$i]['fiction']['fId'] = $fId;
            $fictions_info[$i]['fiction']['fName'] = $fiction_info['fName'];
            $fictions_info[$i]['fiction']['fCover'] = $fiction_info['fCover'];
            //重复阅读的信息
            //小说id
            $fictions_info[$i]['readagain']['fId'] = $fId;
            //当前卷
            $fictions_info[$i]['readagain']['book'] = $book;
            //当前话数
            $fictions_info[$i]['readagain']['bookName'] = '第'.$book.'卷';
            //当前章数
            $fictions_info[$i]['readagain']['chapter'] = $chapter;
            //当前章节名称
            $fictions_info[$i]['readagain']['chapterName'] = $chapter_info['fChapterName'];
            //获取当前卷章节数
            $fictions_info[$i]['readagain']['length'] = count($book_info);
            //当前小说阅读的位置
            $fictions_info[$i]['fiction']['uFReading'] = '看到第'.$book.'卷第'.$chapter.'章';
            //小说的储存路径
            $fictions_info[$i]['readagain']['readurl'] = $fiction_info['fSaveurl'].$book.'/'.$chapter.'.txt';
            $i++;
        }
        return $fictions_info;
    }

    //单独处理某一小说阅读历史
    public function Deal_OneFictionRecord($fictions_record){
        $fictions_info = array();
        $fId = $fictions_record['fId'];
        //将小说历史的集数页数进行分割
        $fiction_record = explode('/', $fictions_record['uFReading']);  //分离1/1
        $book = $fiction_record['0'];    //1 第一卷
        $chapter = $fiction_record['1'];       //1 第一章
        //获取小说的名字和封面、名字、卷数
        $fiction_info = Fiction::getRecordInfoByfId($fId);
        //获取当前章节的详细信息
        $chapter_info = FictionChapter::getChapterName($fId, $book, $chapter);
        //获取当前卷的章节数量
        $chapter_count = FictionChapter::getChapter($fId, $book);
        $chapter_count = count($chapter_count);
        //当前卷名称
        $fictions_info['bookName'] = '第'.$book.'卷';
        //当前章节
        $fictions_info['chapter'] = $chapter;
        //获取当前卷的总章数
        $fictions_info['length'] = $chapter_count;
        //当前图片阅读的位置
        $fictions_info['uFReading'] = '看到第'.$book.'卷第'.$chapter.'章';
        //小说的储存路径
        $fictions_info['readurl'] = $fiction_info['fSaveurl'].$book.'/'.$chapter.'.txt';
        return $fictions_info;
    }

    //处理最新更新的小说信息
    public function Deal_UpdateFictions($fictions){
        $length = count($fictions);
        for($i = 0; $i < $length; $i++){
            $book = $fictions[$i]['fNowupdate'];
            $fictions[$i]['fNowupdate'] = '已更新到第'.$book.'卷';
        }
        return $fictions;
    }
}